package com.tungse.redisson;

import com.tungse.redisson.cfg.RedissonConfig;
import org.redisson.api.RPatternTopic;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;

/**
 * @Author : Tungse
 * @Date: 2025/7/8 17:00
 * @Description:
 */
public class RPublisherTest {
    RedissonClient redissonClient;
    public RPublisherTest() {
        redissonClient = new RedissonConfig().redissonClient();
    }

    public static void main(String[] args) {
        RPublisherTest rPublisher = new RPublisherTest();

        // 订阅频道
        rPublisher.subscribeExactChannel();
        rPublisher.subscribePatternChannel();
        // 发布消息
        rPublisher.publish("news.sports", "中国队夺冠！"); // 精确频道消息
        rPublisher.publish("news.tech", "AI突破新进展！"); // 匹配模式频道
    }


    public void publish(String topicName, String message) {
        RTopic topic = redissonClient.getTopic(topicName);
        long receivers = topic.publish(message); // 返回收到消息的客户端数量
        System.out.println("消息已发布，接收客户端数: " + receivers);

//        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("news.sports");
//        redissonClient.getDelayedQueue(blockingQueue).offer(message + "延时消息", 10, TimeUnit.SECONDS);

    }


    // 订阅精确频道
    public void subscribeExactChannel() {
        String channel = "news.sports";
        RTopic topic = redissonClient.getTopic(channel);
        topic.addListener(String.class, (charSequence, msg) -> {
            System.out.println("[精确频道] 收到消息: " + msg + "，频道: " + charSequence);
        });
    }

    // 订阅通配符频道（模式匹配）
    public void subscribePatternChannel() {
        String pattern = "news.*"; // 匹配所有以 "news." 开头的频道
        RPatternTopic patternTopic = redissonClient.getPatternTopic(pattern);
        patternTopic.addListener(String.class, (patternStr, channel, msg) -> {
            System.out.println("[模式匹配] 频道: " + channel + "，消息: " + msg);
        });
    }
}
